const express = require("express")
const router = express.Router()
const { searchPDF, deletePDF, updatePDF, searchPDFfromId, updatePDFGoodNum, updatePDFuploadNum } = require("../control/PDF")
const { SuccessModel, ErrorModel } = require("../model/resModel")
const passport = require("passport")
const fs = require('fs')
const path = require("path")

router.post("/search", async (req, res) => {
  let data = await searchPDF(req, res)
  if (data.length > 0) {
    res.json(new SuccessModel(data, "查找成功"))
  } else {
    res.json(new ErrorModel("查找失败"))
  }
})
router.post("/del", async (req, res) => {
  let data = await deletePDF(req, res)
  if (data && data.affectedRows > 0) {
    res.json(new SuccessModel("删除成功"))
  } else {
    res.json(new ErrorModel("删除失败"))
  }
})
router.get("/download", async (req, res) => {
  let data = await searchPDFfromId(req, res)
  if (data.length > 0 && data[0].pdf) {
    let num = data[0].pdf.indexOf("?")
    let next1 = data[0].pdf.substring(num)
    let next2 = next1.split("&")[0].split("=")[1]
    let next3 = "./" + next2
    if (fs.existsSync(next3)) {
      console.log("start download");
      var paths = path.join(__dirname, '../' + next3);
      // var f = fs.createReadStream(paths,{
      //   encoding:"utf-8"
      // });
      // res.set({
      //   "Content-Type":"application/octet-stream",//告诉浏览器这是一个二进制文件
      //   'Content-Disposition': 'attachment;filename='+encodeURIComponent('zz.pdf')
      // });
      // f.pipe(res);
      res.download(paths,'zz.pdf')
    }
  }
})

router.get("/addGoodNum", async (req,res)=>{
  let data = await searchPDFfromId(req,res)
  let Num = {uploadNum:data[0].uploadNum*1,seeNum:data[0].seeNum*1}
  let updataData = await updatePDFGoodNum(req,res,Num)
  if (updataData&&updataData.affectedRows > 0) {
    res.json(new SuccessModel("更新成功"))
  } else {
    res.json(new ErrorModel("更新失败"))
  }
})
router.get("/addUploadNum", async (req,res)=>{
  let data = await searchPDFfromId(req,res)
  let Num = {uploadNum:data[0].uploadNum*1,seeNum:data[0].seeNum*1}
  let updataData = await updatePDFuploadNum(req,res,Num)
  if (updataData&&updataData.affectedRows > 0) {
    res.json(new SuccessModel("更新成功"))
  } else {
    res.json(new ErrorModel("更新失败"))
  }
})
router.post("/update", async (req, res) => {
  let data = await updatePDF(req, res)
  if (data && data.affectedRows > 0) {
    res.json(new SuccessModel("更新成功"))
  } else {
    res.json(new ErrorModel("更新失败"))
  }
})
module.exports = router